#include "collisionsystem.h"
#include "c_lua_interface.h"

void CCollisionSystem::HandleEntityCollision()
{
	
	CCollisionReport cr;
	
	if( m_pPlayerEntity && m_pEntityFactory->GetStateVec()->EntityCollidingWithEntities( m_pPlayerEntity, cr ) )
	{
		
				
		for( int j = 0; j < cr.count(); j++ )
		{
			
			CCollisionData & cd = cr[j];

			Vector2D pos = m_pPlayerEntity->GetPos();
			Vector2D dist = cd.minTransAxis * cd.minTransDist;
			
			dist.ToInt();
			
			m_pPlayerEntity->SetPos( pos + dist );
			
			Lua::EntityOnTouch( cd.recID, m_pPlayerEntity->GetUniqueID() );
		
		}
		
	}
	
}

void CCollisionSystem::HandleMapCollision()
{
	
	if( !m_pGameMap )
		return;
	
	CCollisionReport cr;
	
	cr.m_MaxData = 2;
	
	if( m_pPlayerEntity && m_pGameMap->EntityCollidingWithMap( m_pPlayerEntity, cr ) )
	{
		
		for( int j = 0; j < cr.count(); j++ )
		{

			CCollisionData & cd = cr[j];

			Vector2D pos = m_pPlayerEntity->GetPos();
			Vector2D dist = cd.minTransAxis * cd.minTransDist;
			
			m_pPlayerEntity->SetPos( pos + dist );
		
		}
		
	}
	
	CEntityStateVec * ev = m_pEntityFactory->GetStateVec();
	
	if( !ev )
		return;
	
	ev->BeginIterate();
	CEntity * e = NULL;
	
	while( ( e = ev->IterateNextEntity() ) != NULL  )
	{
		
		if( !e || e == m_pPlayerEntity )
			continue;
		
		CCollisionReport ecr;

		m_pGameMap->EntityCollidingWithMap( e, ecr );
		
		for( int j = 0; j < ecr.count(); j++ )
		{
			
			CCollisionData & cd = ecr[j];

			Vector2D pos = e->GetPos();
			Vector2D dist = cd.minTransAxis * cd.minTransDist;
			
			e->SetPos( pos + dist );
		
		}
		
	}
	
}

